package com.xunkids.bos.migration.component.log;

import org.apache.logging.log4j.Level;
import org.apache.logging.slf4j.Log4jLoggerFactory;
import org.apache.logging.slf4j.Log4jMDCAdapter;
import org.apache.logging.slf4j.Log4jMarkerFactory;
import org.slf4j.ILoggerFactory;
import org.slf4j.IMarkerFactory;
import org.slf4j.helpers.Util;
import org.slf4j.spi.MDCAdapter;
import org.slf4j.spi.SLF4JServiceProvider;

import java.util.Arrays;


/**
 * 适配 slf4j 2.x
 *
 * @author baiyanlong
 * @version 1.0.0
 * @since 2022/8/30 19:19
 */
public class Log4j2ServiceProvider implements SLF4JServiceProvider {

    public static String REQUESTED_API_VERSION = "2.0";

    private ILoggerFactory loggerFactory;
    private IMarkerFactory markerFactory;
    private MDCAdapter mdcAdapter;

    public Log4j2ServiceProvider() {
        try {
            @SuppressWarnings("unused")
            Level level = Level.TRACE;
        } catch (NoSuchFieldError error) {
            Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also https://www.slf4j.org/codes.html#log4j_version");
        }
        String log4J2EnvNames = System.getenv("LOG4J2_ENV_NAMES");
        String[] envNames;
        if (log4J2EnvNames != null && !"".equals(log4J2EnvNames)) {
            envNames = log4J2EnvNames.split(",");
        } else {
            envNames = new String[]{"PROJECT_CODE_LOG_LEVEL", "PROJECT_LOG_LEVEL", "LOG_LAYOUT_PATTERN", "LOG_FILE_PATH", "LOG_FILE_NAME", "DEV_LOG_LEVEL"};
        }
        if (envNames.length > 0) {
            Arrays.stream(envNames).forEach(name -> {
                String envValue = System.getenv(name);
                if (envValue != null) {
                    System.setProperty(name, envValue);
                }
            });
        }
    }

    @Override
    public ILoggerFactory getLoggerFactory() {
        return loggerFactory;
    }

    @Override
    public IMarkerFactory getMarkerFactory() {
        return markerFactory;
    }

    @Override
    public MDCAdapter getMDCAdapter() {
        return mdcAdapter;
    }

    @Override
    public String getRequestedApiVersion() {
        return REQUESTED_API_VERSION;
    }

    @Override
    public void initialize() {
        markerFactory = new Log4jMarkerFactory();
        loggerFactory = new Log4jLoggerFactory();
        mdcAdapter = new Log4jMDCAdapter();
    }

}
